from common.response import Response, response2dict
from models import Comment, db, Book
from util.jsonUtil import comment2dict


def get_comments(id):
    comments = Comment.query.filter_by(book_id=id).all()
    print(len(comments))
    code = "200"
    msg = "查询成功"
    data = [comment2dict(comment) for comment in comments]
    response = Response(code, msg, data)
    return response2dict(response)


def creat_comments(comment0):
    db.session.add(comment0)
    db.session.commit()
    a = 0
    b = 0
    comments = Comment.query.filter_by(book_id=comment0.book_id).all()
    for comment in comments:
        if comment.score == -1.0:
            print(comment.id)
        else:
            a += comment.score
            b += 1
    a = a / b
    book = Book.query.filter_by(id=comment0.book_id).first()
    book.score = a
    db.session.commit()
    code = "200"
    msg = "添加成功"
    data = comment2dict(comment0)
    response = Response(code, msg, data)
    return response2dict(response)


def delete_comment(id):
    comment0 = Comment.query.filter_by(id=id).first()
    db.session.delete(comment0)
    db.session.commit()
    a = 0
    b = 0
    comments = Comment.query.filter_by(book_id=comment0.book_id).all()
    for comment in comments:
        if comment.score == -1.0:
            print(comment.id)
        else:
            a += comment.score
            b += 1
    a = a / b
    book = Book.query.filter_by(id=comment0.book_id).first()
    book.score = a
    db.session.commit()
    code = "200"
    msg = "删除成功"
    data = comment2dict(comment0)
    response = Response(code, msg, data)
    return response2dict(response)
